package com.ihealthway.all.groupbuy.services;

import com.ihealthway.all.groupbuy.vo.Reward;
import com.ihealthway.all.utils.Utils;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.util.*;

/**
 * Reward Info service
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@IocBean(fields = {"dao"})
public class RewardInfoService extends BaseService<Reward> {

    private static final Log logger = Logs.get();

    public void increaseRewardSent(Integer rewardId) {
        Sql sql = Sqls.create("UPDATE gb_reward SET rwd_sent = rwd_sent+1 WHERE rwd_id = @rwdId");
        sql.setParam("rwdId", rewardId);
        try {
            dao().execute(sql);
        } catch (Exception e) {
            logger.error("Update goods sale count fail!!!", e);
        }
    }

    public Reward add(Reward reward) {
        reward.setRewardSent(0);
        reward.setDataStatus("0");
        reward.setCreateTime(new Date());
        try {
            Reward tmp = dao().fastInsert(reward);
            return tmp;
        } catch (Exception e) {
            logger.error("Add new reward info fail!!!", e);
            return null;
        }
    }

    public boolean update(Reward reward) {
        reward.setUpdateTime(new Date());
        try {
            int rows = dao().updateIgnoreNull(reward);
            return (rows>0);
        } catch (Exception e) {
            logger.error("Update reward info fail!!!", e);
            return false;
        }
    }

    public Map<String,Object> getDataList(int page, int rows) {
        return easyuiDGPager(page, rows, null);
    }

    public Reward winLottery() {
        Sql sql = Sqls.create("SELECT * FROM gb_rewards WHERE rwd_cnt<>rwd_sent AND data_status = '0'");
        sql.setEntity(dao().getEntity(Reward.class));
        sql.setCallback(Sqls.callback.entities());
        try {
            dao().execute(sql);
        } catch (Exception e) {
            logger.error("Search enter lottery rewards fail!!!", e);
        }

        Map<Integer, Reward> rwdMap = new HashMap<>();

        int rewardId = 0;
        List<Reward> rewards = sql.getList(Reward.class);
        if (rewards!=null && !rewards.isEmpty()){
            logger.infof("Rewards: %d", rewards.size());
            rewards.forEach(rwd -> {
                rwdMap.put(rwd.getRewardId(), rwd);
            });
            rewardId = Utils.luckLotteryDraw(rewards);
            logger.infof("Win luck draw reward id: %d", rewardId);

            if (rewardId!=0) {
                return rwdMap.get(rewardId);
            }
        }



        return null;
    }
}
